package cn.starrysky108.simpleerp.core.util;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * 资源工具
 *
 * @author Carl Lee
 */
public class ResourceUtil {
    private static final ResourcePatternResolver RESOURCE_RESOLVER = new PathMatchingResourcePatternResolver();

    /**
     * 将给定的多个路径转化为Resource对象
     *
     * @param locations 路径数组
     * @return Resources数组
     */
    public static Resource[] resolveMapperLocations(String[] locations) {
        return Stream.of(Optional.ofNullable(locations).orElse(new String[0]))
                .flatMap(location -> Stream.of(getResources(location))).toArray(Resource[]::new);
    }


    /**
     * 将给定的多个路径转化为Resource对象
     *
     * @param location 路径
     * @return Resource对象
     */
    public static Resource[] getResources(String location) {
        try {
            return RESOURCE_RESOLVER.getResources(location);
        } catch (IOException e) {
            return new Resource[0];
        }
    }

}

